import React, { Component } from 'react';
import Dialog from 'material-ui/Dialog';
import Avatar from 'material-ui/Avatar';

import { Link } from 'react-router';

import CONFIG from '../../config';
import ChatSubmit from './ChatSubmit';
import { moment } from '../Utils/Helper';
import { parseJSON, getMethod, postJsonMethod } from '../../redux/Helper';

import ChatContent from './ChatContent';
export default class Chat extends Component {
  initialState = {
    isLoading: false,
    messages: [],
    nextPageUrl: null,
    detail: '',
  };

  constructor(props) {
    super(props);
    this.state = this.initialState
  }

  componentDidMount() {
    this.chat = this.props.socket;
    // 获取信息
    this.chat.on('new message', (msg) => {
      const arr = [...this.state.messages, msg];
      this.setState({messages: arr})
    });
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.open) {
      this.initFetch(nextProps.chatroomId, nextProps.token);
    }
  }

  /**
   * 初始获取5条聊天记录
   */
  initFetch = (chatroomId, token) => {
    let url = `${CONFIG.apiHost}/api/chat/${chatroomId}?token=${token}`;
    fetch(url, getMethod)
    .then(parseJSON)
    .then(res => {
      if (res.next_page_url) {
        this.setState({isLoading: true})
      }else{
        this.setState({isLoading: false})
      }
      this.setState({
        messages: res.data.reverse(),
        nextPageUrl: res.next_page_url
      });
    });
  };

  /**
   * 关闭时退出房间
   */
  close = () => {
    this.chat.emit('leave chatroom', this.props.chatroomId);
    this.setState(this.initialState);
    this.props.handleClose();
  };

  /**
   * 发送私信
   */
  sendChatMessage = () => {
    if (this.state.detail) {
      let msg = {
        type: 'receive_message',
        user_id: this.props.userId,
        user_name: this.props.userName,
        user_img: this.props.userImg,
        companion_id: this.props.friendId,
        chatroom_id: this.props.chatroomId,
        detail: this.state.detail,
        created_at: moment().format(),
      };
      
      const arr = [...this.state.messages, msg];
      this.setState({messages: arr})
      

      let url = `${CONFIG.apiHost}/api/chat?token=${this.props.token}`;
      fetch(url, postJsonMethod(msg))
      .then(this.setState({detail: ''}))

      this.chat.emit('chat', this.props.chatroomId, msg);
    }
  };

  /**
   * 保存用户输入
   */
  handleDetail = (event, value) => {
    this.setState({detail: value});
  };

  /**
   * 获取历史聊天记录
   */
  fetchMessages = () => {
    if (this.state.nextPageUrl) {
      let arr = this.state.messages;

      let request = '&token='+this.props.token;
      let url = this.state.nextPageUrl + request;

      fetch(url, getMethod)
      .then(parseJSON)
      .then(res => {
        setTimeout(() => {
          this.setState({
            nextPageUrl: res.next_page_url,
            messages: res.data.reverse().concat(arr)
          });
        }, 500)
      })
    }else{
      this.setState({isLoading: false});
    }
  };

  render() {
    return (
      <Dialog
        modal={false}
        ref='dialog'
        open={this.props.open}
        onRequestClose={this.close}
        title={
          <div>
            <Link to={`user/${this.props.friendId}`} style={{
              display: 'block',
              color: 'rgba(0, 0, 0, 0.87)'
            }}>
              <Avatar src={this.props.friendImg} />
              <span style={{
                position: 'absolute',
                left: 76,
                top: 36
              }}>
                {this.props.friendName}
              </span>
            </Link>
          </div>
        }
        actions={
          <ChatSubmit
            value={this.state.detail}
            color500={this.props.color500}
            handleDetail={this.handleDetail}
            sendChatMessage={this.sendChatMessage}
          />
        }
        autoScrollBodyContent={false}
        autoDetectWindowHeight={true}
        contentStyle={{
          width: this.props.isSmallViewport ? '100%' : 560
        }}
        bodyStyle={styles.bodyStyle}
        overlayStyle={styles.overlayStyle}
        actionsContainerStyle={{padding: 0}}
        titleStyle={{
          fontSize: 16,
          lineHeight: 'none',
          borderBottomStyle: 'solid',
          borderBottomColor: 'rgb(224, 224, 224)',
          borderBottomWidth: 1,
        }}
      >
        <ChatContent
          userId={this.props.userId}
          userName={this.props.userName}
          userImg={this.props.userImg}
          friendId={this.props.friendId}
          friendName={this.props.friendName}
          friendImg={this.props.friendImg}
          messages={this.state.messages}
          nextPageUrl={this.state.nextPageUrl}
          fetchMessages={this.fetchMessages}
        />
      </Dialog>
    );
  }
};

const styles = {
  overlayStyle: {
    backgroundColor: 'rgba(0,0,0,0.12)'
  },
  bodyStyle: {
    padding: 0,
    maxWidth: 560,
    display: 'flex',
    flexDirection: 'column',
  },
};
